<?php


namespace app\admins\controller;


use app\BaseController;
use app\Request;
use app\validate\AdminCheck;
use app\validate\UserCheck;
use think\exception\ValidateException;
use think\facade\Db;

class User extends BaseController
{
    protected $middleware = [\app\middleware\Check::class];
//    渲染视图
    public function index()
    {
        return view();
    }

    //    删除用户
    public function delete()
    {
        if(request()->isGet()){
            $data = input('get.');
            Db::name('user')->where('id',$data['id'])->delete();

        }

    }

    //    分页展示
    public function article(Request $request){

//        查询条件
        $where = [];
        if (!empty($request->param('name'))) {
            $where[] = ['name|id', 'like', "%{$request->param('name')}%"];
        }
        //获取每页显示的条数
        $limit= $request->param('limit');
        //获取当前页数
        $page= $request->param('page');
        $list = Db::name('user')
            ->where($where)
            ->paginate($limit,false,['page'=>$page])
            ->toArray();
        return json(['code'=>0,'msg'=>'','count'=>$list['total'],'data'=>$list['data']]);

    }

    //    添加用户
    public function addUser(){
        $data = request()->param();
        try {
            $res = validate(UserCheck::class)->check($data);
            $data1 = [
                'name' => $data['name'],
                'password' =>  md5('dytsyq'.$data['password']),
                'phone'     => $data['mobile'],
                'create_at' => $data['create_at'],
            ];
            $Db = Db::name('user');
            if($Db->where('name',$data['name'])->find()) {
                return  json(["state"=>204,"message"=>"用户名不能重复"]);
            }
            $ret = $Db->insert($data1);
//             return $Db->getLastSql();
            if($ret){
                return  json(["state"=>200]);
            }
            else{
                return json(["state"=>204,"message"=>'添加用户失败']);
            }

        } catch (ValidateException $e) {
            return  json(["state"=>204,"message"=>$e->getError()]);
        }

    }
}